package com.heima.wemedia.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/6 22:23
 * 自媒体过滤器
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String path = request.getURI().getPath();
        // 如果登录就放行
        if (path.contains("/login")){
            return chain.filter(exchange);
        }
        // 如果不是就校验token
        String token = request.getHeaders().getFirst("token");

        // 判断token
        if (StringUtils.isEmpty(token)){
            // 设置状态未认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 返回
            return response.setComplete();
        }

        try {
            // 存在token, 判断是否正确, 抛出异常就是token不正确
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            /**
             *   拦截器的作用：从header中获取用户存入当前线程
             *      1. token解析为用户存入header
             *      2. 路由
             */

            // 获取token解析后中的用户信息
            Object userId = claimsBody.get("id");
            // 在head中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            // 重置header
            exchange.mutate().request(serverHttpRequest).build();


            // 判断是否超时, 1或者是2就是超时
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 放行
        return chain.filter(exchange);
    }

    /**
     * 优先级值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
